package cn.lyh.edu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lyh.exception.BadRequestException;
import cn.lyh.edu.domain.EduBanner;
import cn.lyh.edu.repository.EduBannerRepository;
import cn.lyh.edu.service.IEduBannerService;
import cn.lyh.edu.service.dto.BannerQueryCriteria;

import cn.lyh.utils.PageUtil;
import cn.lyh.utils.QueryHelp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class EduBannerServiceImpl implements IEduBannerService {
    private final EduBannerRepository eduBannerRepository;

    public EduBannerServiceImpl(EduBannerRepository eduBannerRepository) {
        this.eduBannerRepository = eduBannerRepository;
    }

    /**
     * 获取轮播图列表数据
     * @param queryCriteria
     * @param pageable
     * @return
     */
    @Override
    public Object getList(BannerQueryCriteria queryCriteria, Pageable pageable) {
        Page<EduBanner> page= eduBannerRepository.findAll((root, query, criteriaBuilder)->
                QueryHelp.getPredicate(root,queryCriteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page);
    }

    /**
     * 新增轮播图
     * @param eduBanner
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBanner(EduBanner eduBanner) {
        EduBanner dbEduBanner =  eduBannerRepository.save(eduBanner);
        if(dbEduBanner.getId()==null||dbEduBanner.getId()==0){
            throw new BadRequestException("新增轮播图失败");
        }
    }

    /**
     * 根据ID获取轮播图详情信息
     * @param id
     * @return
     */
    @Override
    public EduBanner getById(Long id) {
        return eduBannerRepository.findById(id).orElseGet(EduBanner::new);
    }

    /**
     * 更新轮播图信息
     * @param eduBanner
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editBanner(EduBanner eduBanner) {
        EduBanner dbEduBanner =  eduBannerRepository.getReferenceById(eduBanner.getId());
        BeanUtil.copyProperties(eduBanner,dbEduBanner, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        eduBannerRepository.save(dbEduBanner);
    }

    /**
     * 删除轮播图信息
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        eduBannerRepository.deleteById(id);
    }

    /**
     * 获取所有轮播图类型
     * @return
     */
    @Override
    public List<EduBanner> getAll() {
        return eduBannerRepository.findAll();
    }


    
}
